package com.xinqi.common.third.wx.help;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xinqi.common.third.wx.config.WxConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

@Log4j2
@Component
@RequiredArgsConstructor
public class WxHelp {

    private final WxConfig wxConfig;

    public String getToken() {
        String path = "token?grant_type=client_credential&appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getAppSecret();
        String body = HttpUtil.createGet(wxConfig.getWx_gzh_api() + path).execute().body();
        log.info("获取了token,返回数据" + body);
        JSONObject object = JSON.parseObject(body);
        //获取token
        String token = object.getString("access_token");
        return token;
    }

    public String getJsapiTicket(String accessToken) {
        String path = "ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        String body = HttpUtil.createGet(wxConfig.getWx_gzh_api() + path).execute().body();
        log.info("获取了JsapiTicket,返回数据" + body);
        JSONObject object = JSON.parseObject(body);
        //获取ticket
        String ticket = object.getString("ticket");
        //错误码
        Integer errCode = object.getInteger("errcode");
        log.info("微信凭证：{}", errCode);
        return ticket;
    }

    public String getAppId() {
        return wxConfig.getAppId();
    }

    public String getWxGZH() {
        return wxConfig.getWx_gzh_api();
    }

}
